package com.lzdongrui.backend.service.impl;

import java.util.List;

import com.lzdongrui.backend.domain.College;
import com.lzdongrui.backend.domain.dto.MajorDTO;
import com.lzdongrui.backend.domain.vo.MajorVO;
import com.lzdongrui.backend.mapper.CollegeMapper;
import com.lzdongrui.backend.service.ICollegeService;
import com.lzdongrui.common.exception.ServiceException;
import com.lzdongrui.common.utils.DateUtils;
import com.lzdongrui.common.utils.StringUtils;
import com.lzdongrui.common.utils.bean.BeanValidators;
import com.lzdongrui.common.utils.snowid.SnowflakeIdWorker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lzdongrui.backend.mapper.MajorMapper;
import com.lzdongrui.backend.domain.Major;
import com.lzdongrui.backend.service.IMajorService;

import javax.validation.Validator;

/**
 * 专业Service业务层处理
 * 
 * @author wyh
 * @date 2023-05-05
 */
@Service
public class MajorServiceImpl implements IMajorService
{
    private static final Logger log = LoggerFactory.getLogger(MajorServiceImpl.class);

    @Autowired
    private MajorMapper majorMapper;

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    @Autowired
    protected Validator validator;

    @Autowired
    private CollegeMapper collegeMapper;

    /**
     * 查询专业
     * 
     * @param id 专业主键
     * @return 专业
     */
    @Override
    public Major selectMajorById(Long id)
    {
        return majorMapper.selectMajorById(id);
    }

    /**
     * 查询专业列表
     * 
     * @param majorDTO 专业
     * @return 专业
     */
    @Override
    public List<MajorVO> selectMajorList(MajorDTO majorDTO)
    {
        return majorMapper.selectMajorList(majorDTO);
    }

    @Override
    public List<Major> selectMajorAllList(MajorDTO majorDTO) {
        return majorMapper.selectMajorAllList(majorDTO);
    }

    @Override
    public String importMajor(List<MajorDTO> majorDTOS, boolean updateSupport, Long operator) {
        if (StringUtils.isNull(majorDTOS) || majorDTOS.size() == 0) {
            throw new ServiceException("导入专业数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (MajorDTO majorDTO : majorDTOS) {
            try {
                //查询学院数据是否存在
                College collegeInfo = collegeMapper.selectCollegeInfoByCode(majorDTO.getCollegeCode());
                if(!StringUtils.isNull(collegeInfo)){
                    //查询专业的数据是否有重复（包含code、名称）
                    Major major = new Major();
                    BeanUtils.copyProperties(majorDTO, major);
                    Major n = majorMapper.selectMajorInfo(major);
                    if (StringUtils.isNull(n)) {
                        Major major1 = new Major();
                        BeanUtils.copyProperties(majorDTO, major1);
                        major1.setId(snowflakeIdWorker.nextId());
                        major1.setCollegeId(collegeInfo.getId());
                        major1.setOperator(operator);
                        BeanValidators.validateWithException(validator, major1);
                        this.insertMajor(major1);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、专业Code " + majorDTO.getMajorCode() + "、学院 " + majorDTO.getName() + " 导入成功");
                    } else if (updateSupport) {
                        Major major2 = new Major();
                        BeanUtils.copyProperties(majorDTO, major2);
                        major2.setId(n.getId());
                        major2.setCollegeId(collegeInfo.getId());
                        major2.setOperator(operator);
                        BeanValidators.validateWithException(validator, major2);
                        this.updateMajor(major2);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、专业Code " + majorDTO.getMajorCode() + "、学院 " + majorDTO.getName() + " 更新成功");
                    } else {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、专业 " + majorDTO.getName() + " 已存在");
                    }
                }else{
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、学院Code " + majorDTO.getCollegeCode() + " 不存在");
                }
                //返回异常数据
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、专业 " + majorDTO.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 新增专业
     * 
     * @param major 专业
     * @return 结果
     */
    @Override
    public int insertMajor(Major major)
    {
        int ret = 0;
        //查询专业的数据是否有重复（包含code、名称）
        Major n = majorMapper.selectMajorInfo(major);
        if(StringUtils.isNull(n)){
            major.setCreateTime(DateUtils.getNowDate());
            major.setId(snowflakeIdWorker.nextId());
            ret = majorMapper.insertMajor(major);
        }else{
            throw new ServiceException("请检查专业代码和名称是否有重复");
        }
        return ret;
    }

    /**
     * 修改专业
     * 
     * @param major 专业
     * @return 结果
     */
    @Override
    public int updateMajor(Major major)
    {
        int ret = 0;
        //查询专业的数据是否有重复（包含code、名称）
        Major n = majorMapper.selectMajorInfo(major);
        if(n.getId().equals(major.getId())){
            major.setUpdateTime(DateUtils.getNowDate());
            ret = majorMapper.updateMajor(major);
        }else{
            throw new ServiceException("请检查专业代码和名称是否有重复");
        }
        return ret;
    }

    /**
     * 批量删除专业
     * 
     * @param ids 需要删除的专业主键
     * @return 结果
     */
    @Override
    public int deleteMajorByIds(Long[] ids)
    {
        return majorMapper.deleteMajorByIds(ids);
    }

    /**
     * 删除专业信息
     * 
     * @param id 专业主键
     * @return 结果
     */
    @Override
    public int deleteMajorById(Long id)
    {
        return majorMapper.deleteMajorById(id);
    }

}
